/**
 * 
 */
package vn.com.tiz.DocumentZ.view;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Scroller;

public class WipeView extends ViewGroup {
		
	public static interface OnScreenSwitchListener {
		void onScreenSwitched(int screen);		
	}

	private static final int SNAP_VELOCITY = 1000;
	private static final int INVALID_SCREEN = -1;
	private static final int X_DISTANCE = 100;

	private Scroller mScroller;
	private VelocityTracker mVelocityTracker;

	private final static int TOUCH_STATE_REST = 0;
	private final static int TOUCH_STATE_SCROLLING = 1;

	private int mTouchState = TOUCH_STATE_REST;

	private float mLastMotionX;
	private int mTouchSlop;
	private int mMaximumVelocity;
	private int mCurrentScreen;
	private int mNextScreen = INVALID_SCREEN;

	
	private boolean mJustInterceptedAndIgnored = false;
	private boolean mMostlyScrollingInX = false;
	private boolean mMostlyScrollingInY = false;
	
	private boolean mFirstLayout = true;
	public boolean isScrolling = false;
	
	float lastX = 0;
	float xDistance = 0;
	int mMotionStartX = 0;
	int mMotionStartY = 0;
	

	private OnScreenSwitchListener mOnScreenSwitchListener;

	public WipeView(Context context) {
		super(context);
		init();
	}

	public WipeView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	private void init() {
		
		LayoutParams lparam = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
		setLayoutParams(lparam);
		
		mScroller = new Scroller(getContext());

		final ViewConfiguration configuration = ViewConfiguration.get(getContext());
		mTouchSlop = configuration.getScaledTouchSlop();
		mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();	
	}
	
	
	

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);

		final int width = MeasureSpec.getSize(widthMeasureSpec);
		final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
		
		
		
		if (widthMode != MeasureSpec.EXACTLY) {
			//throw new IllegalStateException("ViewSwitcher can only be used in EXACTLY mode.");
		}

		final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
		if (heightMode != MeasureSpec.EXACTLY) {
			//throw new IllegalStateException("ViewSwitcher can only be used in EXACTLY mode.");
		}

		// The children are given the same width and height as the workspace
		final int count = getChildCount();
		for (int i = 0; i < count; i++) {
			getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
		}

		if (mFirstLayout) {
			scrollTo(mCurrentScreen * width, 0);
			mFirstLayout = false;
		}
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		int childLeft = 0;

		final int count = getChildCount();
		for (int i = 0; i < count; i++) {
			final View child = getChildAt(i);
			if (child.getVisibility() != View.GONE) {
				final int childWidth = child.getMeasuredWidth();
				child.layout(childLeft, 0, childLeft + childWidth, child.getMeasuredHeight());
				childLeft += childWidth;
			}
		}
	}
	
	private void detectMostlyScrollingDirection(MotionEvent ev)
	{
		if(!mMostlyScrollingInX && !mMostlyScrollingInY) //if we dont know which direction we're going yet
		{
			float xDistance = Math.abs(mMotionStartX - ev.getX());
			float yDistance = Math.abs(mMotionStartY - ev.getY());
			
			if(yDistance>xDistance+5)
			{
				mMostlyScrollingInY = true;
			}
			else if(xDistance>yDistance+5)
			{
				mMostlyScrollingInX = true;
			}
		}
	}
	
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev)
	{
		boolean result = super.onInterceptTouchEvent(ev);
	
		
		
		if(ev.getAction() == MotionEvent.ACTION_DOWN)
		{
			mMotionStartX = (int) ev.getX();
			mMotionStartY = (int) ev.getY();
			if(!mJustInterceptedAndIgnored)
			{
				mMostlyScrollingInX = false;
				mMostlyScrollingInY = false;
			}
		}
		else if(ev.getAction()==MotionEvent.ACTION_MOVE)
		{
			detectMostlyScrollingDirection(ev);
		}
		
		if(mMostlyScrollingInY)
		{
			return false;
		}
		if(mMostlyScrollingInX)
		{
			mJustInterceptedAndIgnored = true;
			return true;
		}
		
		return result;
	}

	
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		
		//boolean mSendingDummyMotionEvent = false;				
		
//		if(mScroller.isFinished())
//			isScrolling = false;
//		else
//		{
//			//Log.e("TrungTT","is scrolling....");
//			return false;
//		}
		
		
		//if(isScrolling)
		//	return true;
		
		if (mVelocityTracker == null) {
			mVelocityTracker = VelocityTracker.obtain();
		}
		mVelocityTracker.addMovement(ev);

		final int action = ev.getAction();
		final float x = ev.getX();		
				
		
		switch (action) {
			
		case MotionEvent.ACTION_DOWN:
		
			if (!mScroller.isFinished()) {
				mScroller.abortAnimation();
			}
					
			// Remember where the motion event started
			mLastMotionX = x;
			mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING;
							
			lastX = ev.getX();	
			mMotionStartX = (int) ev.getX();
			mMotionStartY = (int) ev.getY();
			
			break;

		case MotionEvent.ACTION_MOVE:	
			final int xDiff = (int) Math.abs(x - mLastMotionX);
			boolean xMoved = xDiff > mTouchSlop;

			if (xMoved) {
				// Scroll if the user moved far enough along the X axis
				mTouchState = TOUCH_STATE_SCROLLING;				
			}

			if(mJustInterceptedAndIgnored)
			{				
				dispatchTouchEvent(MotionEvent.obtain(ev.getDownTime(), ev.getEventTime(), MotionEvent.ACTION_DOWN,
						mMotionStartX, mMotionStartY, ev.getPressure(), ev.getSize(), ev.getMetaState(), ev.getXPrecision(), 
						ev.getYPrecision(), ev.getDeviceId(), ev.getEdgeFlags()));
				mJustInterceptedAndIgnored = false;
				
				break;
			}
			
			xDistance = lastX - ev.getX();
			if (mTouchState == TOUCH_STATE_SCROLLING) {	
				final int deltaX = (int) (mLastMotionX - x);
				mLastMotionX = x;

				final int scrollX = getScrollX();			
				if (deltaX < 0) {
					if (scrollX > 0) {
						scrollBy(Math.max(-scrollX, deltaX), 0);
					}
				} else if (deltaX > 0) {
					final int availableToScroll = getChildAt(getChildCount() - 1).getRight() - scrollX - getWidth();
					
					if (availableToScroll > 0) {
						
						scrollBy(Math.min(availableToScroll, deltaX), 0);
					}
				}
			}
			break;

		case MotionEvent.ACTION_UP:
			if (mTouchState == TOUCH_STATE_SCROLLING) {
				final VelocityTracker velocityTracker = mVelocityTracker;
				velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
				int velocityX = (int) velocityTracker.getXVelocity();

				if (velocityX > SNAP_VELOCITY && mCurrentScreen > 0) {
					// Fling hard enough to move left
					snapToScreen(mCurrentScreen - 1);
				} else if (velocityX < -SNAP_VELOCITY && mCurrentScreen < getChildCount() - 1) {
					// Fling hard enough to move right
					snapToScreen(mCurrentScreen + 1);
				} else {
					snapToDestination();
				}

				if (mVelocityTracker != null) {
					mVelocityTracker.recycle();
					mVelocityTracker = null;
				}
			}

			mTouchState = TOUCH_STATE_REST;

			break;

		case MotionEvent.ACTION_CANCEL:
			mTouchState = TOUCH_STATE_REST;
		}

		return true;
	}

	public void snapToDestination() {
		final int screenWidth = getWidth();
		final int whichScreen = (getScrollX() + (screenWidth / 2)) / screenWidth;

		snapToScreen(whichScreen);
	}

	public void snapToScreen(int whichScreen) {
				
		if (!mScroller.isFinished())
			return;

		isScrolling = true;
		whichScreen = Math.max(0, Math.min(whichScreen, getChildCount() - 1));

		mNextScreen = whichScreen;

		final int newX = whichScreen * getWidth();
		final int delta = newX - getScrollX();
		//Log.d("TrungTT","Duration:"+ Math.abs(delta) * 2);
		mScroller.startScroll(getScrollX(), 0, delta, 0, Math.abs(delta) * 2);
		//mScroller.startScroll(getScrollX(), 0, delta, 0, 1500);
		
		invalidate();
		
	}

	@Override
	public void computeScroll() {
		if (mScroller.computeScrollOffset()) {
			scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
			postInvalidate();
		} else if (mNextScreen != INVALID_SCREEN) {
			mCurrentScreen = Math.max(0, Math.min(mNextScreen, getChildCount() - 1));

			if (mOnScreenSwitchListener != null){
				mOnScreenSwitchListener.onScreenSwitched(mCurrentScreen);
				isScrolling = false;
			}

			mNextScreen = INVALID_SCREEN;
		}
	}

	public int getCurrentScreen() {
		return mCurrentScreen;
	}

	public void setCurrentScreen(int currentScreen) {
		
		//Log.e("TrungTT","setcurrent:"+currentScreen);
		mCurrentScreen = Math.max(0, Math.min(currentScreen, getChildCount() - 1));
		scrollTo(mCurrentScreen * getWidth(), 0);		
		invalidate();
		
	}
	
	public void setOnScreenSwitchListener(OnScreenSwitchListener onScreenSwitchListener) {
		mOnScreenSwitchListener = onScreenSwitchListener;
	}

}
